package application.exportimport;

import dao.inte.CmsPageRepository;
import dao.inte.ConfigurationRepository;
import domain.cms.CmsPage;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * Provides methods for creating content inventory
 */
@Singleton
public class ContentInventoryMaker {

    @Inject
    private ConfigurationRepository configurationRepository;
    @Inject
    private CmsPageRepository cmsSectionRepository;
    private String contentInvetoryDir;
    private static final String CONTENT_INVENTORY_NAME = "contentInvetory-";
    private static final String CONTENT_INVENTORY_SUFFIX = ".html";
    private static final String DATE_FORMAT_NOW = "yyyy-MM-dd-HH-mm-ss";

    public ContentInventoryMaker() {
    }


    public void generateContentInventory() throws IOException {
        contentInvetoryDir = configurationRepository.getConfig().getContentInvetoryDir();
        if (contentInvetoryDir == null) {
            throw new PathIsNotSetException("contentInvetoryDir is not set");
        }
        File file = createFile();
        WrappedContent wrappedContent = generateContent();
        flushContentAndClose(file, wrappedContent);
    }

    private File createFile() throws IOException {
        String fileName = createFileName();
        File file = new File(contentInvetoryDir + fileName);
        if (file.exists()) {
            deleteFile(file);
        }
        physicallyCreateFile(file);
        return file;
    }

    private String createFileName() {
        String formatedTime = getFormatedTime();
        return CONTENT_INVENTORY_NAME + formatedTime + CONTENT_INVENTORY_SUFFIX;
    }

    private void deleteFile(File file) {
        file.delete();
    }

    private void physicallyCreateFile(File file) throws IOException {
        file.createNewFile();
    }

    private String getFormatedTime() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT_NOW);
        return simpleDateFormat.format(calendar.getTime());
    }

    private void flushContentAndClose(File file, WrappedContent wrappedContent) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
        writer.write(wrappedContent.toString());
        writer.newLine();
        writer.flush();
        writer.close();
    }

    /**
     * Create and fill wrappedContent
     *
     * @return new and filled WrappedContent
     */
    private WrappedContent generateContent() {
        WrappedContent wrappedContent = new WrappedContent();
        List<CmsPage> sections = cmsSectionRepository.findAll();
        for (CmsPage cmsSection : sections) {
            wrappedContent.addPage(cmsSection);
        }
        return wrappedContent;
    }
}
